﻿using System;

namespace Cgd.Shell.Utilities
{
	/// <summary>
	/// 为字符串类提供扩展功能。
	/// </summary>
	public static class StringUtility
	{
		/// <summary>
		/// 将字符串长度限制在<see cref="maxLength"/>个字符之内，超过部分用<see cref="ellipsis"/>所指定的字符串代替。
		/// </summary>
		/// <param name="str"></param>
		/// <param name="maxLength">最大长度。</param>
		/// <param name="ellipsis">用于取代超出部分的省略号。</param>
		/// <returns>长度不超过<see cref="maxLength"/>个字符的字符串。</returns>
		public static string LimitLength(this string str, int maxLength, string ellipsis)
		{
			if(str == null)
				throw new ArgumentNullException("str");

			if(maxLength <= 0)
				throw new ArgumentException("最大长度必须为正整数。", "maxLength");

			if (ellipsis == null)
				throw new ArgumentNullException("ellipsis");

			if (ellipsis.Length >= maxLength)
				throw new ArgumentException("最大长度必需大于省略号的长度。", "maxLength");

			if (str.Length > maxLength)
			{
				str = str.Substring(0, maxLength - ellipsis.Length) + ellipsis;
			}

			return str;
		}
	}
}
